<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2019/2/21
 * Time: 9:48
 */

namespace app\api\controller\v1;

use app\api\model\SupplierCompany;
use app\api\service\popularizeService;
use app\api\validate\Popularize as PopularizeValidate;
use app\api\validate\Registered as RegisteredValidate;
use app\common\service\getPhoneInfoService;
use app\lib\exception\ParameterException;
use think\facade\Request;
use Driver\Cache\Redis;

class Popularize
{
    const BUTTON = 0;

    public function __construct()
    {
        if(self::BUTTON == 0){
            throw new ParameterException([
                'code' => 500,
                'msg' => '资源找不到'
            ]);
        }
        return ;
    }
    # 推广第一次发送请求，记录推广，还没有注册
    /**
     * @param from => 来之哪个渠道
     * @param sign => 渠道标识
     * @param ip => 来源ip
     * @param record_id => 记录id from_sign_ timestamp 组成
     * @param type => 产品类型
     * @return \think\response\Json
     * @throws \app\lib\exception\MysqlErrorException
     * @throws \app\lib\exception\ParameterException
     */
    public function popularize()
    {
        (new PopularizeValidate())->goCheck();
        $post_data = Request::post();
        $data = $this->redisListPool($post_data, config('redis.pop'), config('redis.pool_pop_num'));
        if($data == false){
             return json(['msg' => 'Lpush success']);
        }
        $service = new popularizeService();
        $result = $service->listPopularizeToMysql($data);
        return json([
            'msg' => $result
        ]);
    }
    # 推广第二次发送请求，已经注册(允许不同平台出现相同的手机号码)
    public function _registered()
    {
        (new RegisteredValidate)->goCheck();
        $post_data = Request::post();
        $data = $this->redisListPool($post_data, config('redis.reg'), config('redis.pool_reg_num'));
        if($data == false){
            return json(['msg' => 'Lpush success']);
        }
        $service = new popularizeService();
        $result = $service->listRegisteredToMysql($data);
        return json([
            'msg' => $result
        ]);
    }

    # 暂时使用实时更新
    public function registered()
    {
        (new RegisteredValidate)->goCheck();
        $post_data = Request::post();
        $service = new popularizeService();
        $result = $service->_writeRegistered($post_data);
        return json($result);
    }

    /**
     * 设置一个redis_list 左插入数据
     * 设置一个num  每次请求num+1
     * 当num除以2为零时，取list中50个元素并写入到redis，取余不为0时，则把请求的数据插入到list中
     * @param $data post的数据
     * @param $redis_list_key list对应的key
     * @param $pool_num_key 记录当前的请求次数
     * @return array|bool
     */
    private function redisListPool($data, $redis_list_key, $pool_num_key)
    {
        $bool = Redis::FindKeys($pool_num_key);
        if($bool == 0){
            Redis::set($pool_num_key, 0, 0);
            return false;
        }
        $pool_num = Redis::get($pool_num_key);
        $json = json_encode($data);
//        Redis::sAdd(config('redis.record_id'), $data['record_id']);
        if($pool_num % 2 == 0 && $pool_num !== "0"){
            $redis_arr_data = Redis::lRange($redis_list_key, -50, -1);
            Redis::incr($pool_num_key);
            $num = count($redis_arr_data);
            $redis_arr_data[$num] = json_encode($data);
            return $redis_arr_data;
        }else{
            Redis::lpush($redis_list_key, $json);
            Redis::incr($pool_num_key);
            return false;
        }
    }

    /**
     * 检查sign并返回logo
     * @param $from
     * @param $sign
     * @return \think\response\Json
     */
    public function logo($from, $sign)
    {
        $redis_set_key = config('redis.all_sign').$from;
        $sign_status = Redis::sismember($redis_set_key, $sign) ? 1 : -1;
        $redis_hash_key = config('redis.account').$from;
        $logo = Redis::hget($redis_hash_key, 'logo');
        return json([
            'sign_status' => $sign_status,
            'logo' => $logo
        ]);
    }

    /**
     * 通过logo获取下载地址
     * @param $logo
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function appDownload($logo)
    {
        $model = new SupplierCompany();
        $info = $model->where('logo', '=', $logo)
            ->find();
//        $redis_key = config('logo').$logo;
//        $company_name = Redis::hget($redis_key, 'company_name');
        return json(
            [
                'data' => [
                    // 暂时从配置文件读取
                    'company_name'=> config('company.'.$logo),
                    'android_url' => $info['android_url'],
                    'apple_url' => $info['apple_url'],
                    'web_url' => $info['web_url'],
                ],
                'code' => 200
            ]
        );
    }
}